package com.liu.qqserver.server;
import com.liu.qqcommon.Message;
import com.liu.qqcommon.MessageType;
import com.liu.utils.Utility;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

public class SendNewsToAllService implements Runnable {

    @Override
    public void run() {
        //为了多次发送新闻，用while方法
        while (true) {
            System.out.println("请输入服务器要推送的新闻/消息[exit退出]：");
            String news = Utility.readString(100);
            if("exit".equals(news)) {
                break;
            }
            //构建一个Message对象，群发消息
            Message message = new Message();
            message.setMesType(MessageType.MESSAGE_TO_ALL_MES );
            message.setSender("服务器");
            message.setContent(news);
            message.setSendTime(new Date().toString());
            System.out.println("服务器对所有人说：" + news);
            //遍历线程
            HashMap<String, ServerConnectClientThread> hm = ManageServerThreads.getHm();
            Iterator<String> iterator = hm.keySet().iterator();
            while (iterator.hasNext()) {
                String OnLineUserId = iterator.next().toString();
                try {
                    ObjectOutputStream oos = new ObjectOutputStream(hm.get(OnLineUserId).getSocket().getOutputStream());
                    oos.writeObject(message);

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }
}
